package org.jiamandan.com.strategy.listener;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.constant.BizConstant;
import org.jiamandan.com.constant.DXConstant;
import org.jiamandan.com.dto.DXBasicDto;
import org.jiamandan.com.strategy.IDXContextListener;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * DX结算订单
 */
@Service(value = DXConstant.Service.CMD_A02)
@AllArgsConstructor
@Slf4j
public class DXA02IssueChargeStopListenerService implements IDXContextListener {

   // private IOrderChargeService iOrderChargeService;

    @Override
    public void doExecute(DXBasicDto dto, Channel ctx) throws Exception {
        log.info("接收嘉满电-DX获取A02设备停止充电指令(CMD=A02)【"+dto.getDeviceNo()+"】报文:" + JSON.toJSONString(dto));
        //ToDo 结算订单=>
        String data = dto.getData();
        String status = data.substring(2,4);
        String gunNo = data.substring(0,2);
        //todo 结算结算订单
        /*
        if(status.equals("00")){
            log.info("嘉满电-DX关闭设备={},充电端口={}",dto.getDeviceNo(),gunNo);
            QueryWrapper<OrderCharge> query = Wrappers.<OrderCharge>query();
            query.lambda().eq(OrderCharge::getChargePileNo, dto.getDeviceNo());
            query.lambda().eq(OrderCharge::getChargeGunNo, gunNo);
            query.lambda().eq(OrderCharge::getOrderStatus, BizConstant.OrderStatus.CHARGING);
            query.lambda().eq(OrderCharge::getStatus, BizConstant.Status.ACTIVE);
            query.lambda().eq(OrderCharge::getIsDeleted, 0);
            query.lambda().orderByDesc(OrderCharge::getUpdateTime);
            List<OrderCharge> orderCharges = iOrderChargeService.list(query);
            if (orderCharges != null && orderCharges.size() > 1) {
                OrderCharge orderCharge = orderCharges.get(0);
                orderCharge.setStopReason("90");                                        //远程APP关闭
                Integer sumChargeTime = convertToSecond(orderCharge.getSumChargeTime());
                iOrderChargeService.stopDxCharge(orderCharge.getOrderNo(),"07",sumChargeTime,orderCharge.getTotalElectric(),false);
            }
        }*/
    }
    private static int convertToSecond(String time) {
        if (StringUtils.isBlank(time)) {
            return 0;
        }
        String[] times = StringUtils.split(time, ":");
        int hour = Integer.parseInt(times[0]) * 3600;
        int min = Integer.parseInt(times[1]) * 60;
        return (hour + min + Integer.parseInt(times[2]));
    }
}
